package com.iplant.ams.serviceImpl;

import com.iplant.ams.service.DRMService;
import com.iplant.ams.service.basicenum.dms.DMSItemTaskStatus;
import com.iplant.ams.service.basicenum.dms.DMSMaintenanceItemType;
import com.iplant.ams.service.basicenum.dms.DMSMaintenanceLevel;
import com.iplant.ams.service.po.ams.fxt.AMSFrockTool;
import com.iplant.ams.service.po.ams.fxt.AMSMeasureTool;
import com.iplant.ams.service.po.dms.DMSDeviceLedger;
import com.iplant.ams.service.po.dms.DMSDeviceType;
import com.iplant.ams.service.po.dms.fault.DMSFaultBase;
import com.iplant.ams.service.po.dms.maintenance.*;
import com.iplant.ams.serviceImpl.dao.dms.maintenance.*;
import com.iplant.base.po.OutResult;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.ServiceResult;
import com.iplant.base.po.enums.ExceptionTypes;
import com.iplant.base.po.excel.ExcelData;
import com.iplant.base.po.excel.ExcelLineData;
import com.iplant.base.po.excel.ExcelSheetData;
import com.iplant.base.po.excel.MyExcelSheet;
import com.iplant.base.utils.general.CalendarTool;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.orm.ORMUtils;
import com.iplant.base.utils.sql.orm.PoService;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.basic.service.po.bms.qft.BMSQualification;
import com.iplant.basic.service.po.fmc.FMCStation;
import com.iplant.basic.utils.ExcelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DRMServiceImpl implements DRMService {
    private static Logger logger = LoggerFactory.getLogger(DRMServiceImpl.class);

    public DRMServiceImpl() {
        // TODO Auto-generated constructor stub
    }

    private static DRMService Instance = null;

    public static DRMService getInstance() {
        if (Instance == null)
            Instance = new DRMServiceImpl();

        return Instance;
    }

    //region POService
    PoService<DMSMaintenanceRule> mDMSMaintenanceRulePoService = ORMUtils.GetPoService(DMSMaintenanceRule.class);
    PoService<DMSMaintenanceRuleItem> mDMSMaintenanceRuleItemPoService =
            ORMUtils.GetPoService(DMSMaintenanceRuleItem.class);
    PoService<DMSMaintenanceStep> mDMSMaintenanceStepService = ORMUtils.GetPoService(DMSMaintenanceStep.class);
    PoService<AMSFrockTool> mAMSFrockToolService = ORMUtils.GetPoService(AMSFrockTool.class);
    PoService<AMSMeasureTool> mAMSMeasureToolService = ORMUtils.GetPoService(AMSMeasureTool.class);
    PoService<BMSQualification> mBMSQualificationService = ORMUtils.GetPoService(BMSQualification.class);
    PoService<DMSConfiguration> mDMSConfigurationService = ORMUtils.GetPoService(DMSConfiguration.class);
    PoService<DMSDeviceBOM> mDMSDeviceBOMService = ORMUtils.GetPoService(DMSDeviceBOM.class);
    PoService<DMSFaultBase> mDMSFaultBaseService = ORMUtils.GetPoService(DMSFaultBase.class);
    PoService<DMSDeviceType> mDMSDeviceTypeService = ORMUtils.GetPoService(DMSDeviceType.class);
    PoService<DMSMaintenanceItemTask> mDMSMaintenanceItemTaskService =
            ORMUtils.GetPoService(DMSMaintenanceItemTask.class);
    PoService<DMSDeviceLedger> mDMSDeviceLedgerService = ORMUtils.GetPoService(DMSDeviceLedger.class);
    PoService<DMSMaintenanceItem> mDMSMaintenanceItemService = ORMUtils.GetPoService(DMSMaintenanceItem.class);
    PoService<DMSMaintenanceTask> mDMSMaintenanceTaskService = ORMUtils.GetPoService(DMSMaintenanceTask.class);
    PoService<FMCStation> mFMCStationService = ORMUtils.GetPoService(FMCStation.class);
    //endregion

    //region 设备构型

    @Override
    public ServiceResult<Integer> DMS_UpdateConfiguration(BMSEmployee wLoginUser, DMSConfiguration wDMSConfiguration) {
        ServiceResult<Integer> wResult = new ServiceResult<>(0);
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            boolean wIsAdd = wDMSConfiguration.ID == 0;

            wDMSConfiguration.setUserInfo(wLoginUser);
            mDMSConfigurationService.UpdateCheckPo(wLoginUser, wDMSConfiguration, wErrorCode);
            if (wErrorCode.Result != 0) {
                wResult.AddFaultCode(wErrorCode);
                return wResult;
            }
            if (wDMSConfiguration.ID <= 0) {
                return wResult;
            }
            //保存设备构型bom
            if (wIsAdd && wDMSConfiguration.DMSDeviceBOMList != null && wDMSConfiguration.DMSDeviceBOMList.size() > 0) {
                for (DMSDeviceBOM wDMSDeviceBOM : wDMSConfiguration.DMSDeviceBOMList) {
                    wDMSDeviceBOM.ID = 0;
                    wDMSDeviceBOM.setUserInfo(wLoginUser);
                    wDMSDeviceBOM.DeviceID = wDMSConfiguration.DeviceID;
                    wDMSDeviceBOM.ConfigurationID = wDMSConfiguration.ID;
                    wDMSDeviceBOM.AssetInfoID = wDMSConfiguration.AssetInfoID;
                }
                mDMSDeviceBOMService.UpdatePoList(wLoginUser, wDMSConfiguration.DMSDeviceBOMList, wErrorCode);
                wResult.AddFaultCode(wErrorCode);
            }
            ServiceResult<Integer> wServiceResult;
            if (wIsAdd && wDMSConfiguration.MaintenanceItemList != null && wDMSConfiguration.MaintenanceItemList.size() > 0) {
                for (DMSMaintenanceItem wDMSDeviceBOM : wDMSConfiguration.MaintenanceItemList) {
                    wDMSDeviceBOM.ID = 0;
                    wDMSDeviceBOM.setUserInfo(wLoginUser);
                    wDMSDeviceBOM.DeviceID = wDMSConfiguration.DeviceID;
                    wDMSDeviceBOM.ConfigurationID = wDMSConfiguration.ID;
                    wDMSDeviceBOM.AssetInfoID = wDMSConfiguration.AssetInfoID;
                    wServiceResult = this.DMS_UpdateMaintenanceItem(wLoginUser, wDMSDeviceBOM);
                    if (StringUtils.isNotEmpty(wServiceResult.FaultCode))
                        wResult.FaultCode += wServiceResult.FaultCode;
                }
            }
            if (wIsAdd && wDMSConfiguration.DMSConfigurationList != null && wDMSConfiguration.DMSConfigurationList.size() > 0) {
                for (DMSConfiguration wDMSDeviceBOM : wDMSConfiguration.DMSConfigurationList) {
                    wDMSDeviceBOM.ID = 0;
                    wDMSDeviceBOM.setUserInfo(wLoginUser);
                    wDMSDeviceBOM.DeviceID = wDMSConfiguration.DeviceID;
                    wDMSDeviceBOM.ParentID = wDMSConfiguration.ID;
                    wDMSDeviceBOM.AssetInfoID = wDMSConfiguration.AssetInfoID;
                    wServiceResult = this.DMS_UpdateConfiguration(wLoginUser, wDMSDeviceBOM);
                    if (StringUtils.isNotEmpty(wServiceResult.FaultCode))
                        wResult.FaultCode += wServiceResult.FaultCode;
                }
            }
            wResult.AddFaultCode(wErrorCode);
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error(e.toString());
        }
        return wResult;
    }

    @Override
    public ServiceResult<List<DMSConfiguration>> DMS_SelectDeviceConfigurationList(BMSEmployee wLoginUser,
                                                                                   int wDeviceID) {
        ServiceResult<List<DMSConfiguration>> wResult = new ServiceResult<List<DMSConfiguration>>();
        wResult.Result = new ArrayList<>();
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);
            //查询设备配置列表
            List<DMSConfiguration> wConfigurationResult =
                    DMSConfigurationDAO.getInstance().DMS_SelectDeviceConfigurationList(wLoginUser, wDeviceID,
                            wErrorCode);
            if (wErrorCode.Result != 0) {
                wResult.AddFaultCode(wErrorCode);
                return wResult;
            }
            //查询设备下所有BOM列表
            List<DMSDeviceBOM> wDeviceBOMList = DMSDeviceBOMDAO.getInstance().DMS_SelectDeviceBOMList(wLoginUser,
                    wDeviceID, wErrorCode);
            if (wErrorCode.Result != 0) {
                wResult.AddFaultCode(wErrorCode);
                return wResult;
            }
            //查询设备下所有保养点列表
            List<DMSMaintenanceItem> wMaintenanceItemResult =
                    DMSMaintenanceItemDAO.getInstance().DMS_SelectMaintenanceItemList(wLoginUser, wDeviceID,
                            wErrorCode);
            if (wErrorCode.Result != 0) {
                wResult.AddFaultCode(wErrorCode);
                return wResult;
            }
            //查询设备下所有规则列表
            List<DMSMaintenanceRule> wMaintenanceRuleResult =
                    DMSMaintenanceRuleDAO.getInstance().DMS_SelectMaintenanceRuleList(wLoginUser, wDeviceID,
                            wErrorCode);
            if (wErrorCode.Result != 0) {
                wResult.AddFaultCode(wErrorCode);
                return wResult;
            }

            wConfigurationResult.sort(Comparator.comparingInt(o -> (o.ParentID <= 0 ? 0 : 1)));

            //将wConfigurationResult数据根据ParentID整合到wResult.Result中
            for (DMSConfiguration wConfiguration : wConfigurationResult) {

                //将wMaintenanceItemResult数据根据ConfigurationID整合到wConfiguration.MaintenanceItemList中
                for (DMSMaintenanceItem wMaintenanceItem : wMaintenanceItemResult) {
                    if (wMaintenanceItem.ConfigurationID == wConfiguration.ID) {
                        wConfiguration.MaintenanceItemList.add(wMaintenanceItem);
                    }
                }
                //将wDeviceBOMList数据根据ConfigurationID整合到wConfiguration.DMSDeviceBOMList中
                for (DMSDeviceBOM wDeviceBOM : wDeviceBOMList) {
                    if (wDeviceBOM.ConfigurationID == wConfiguration.ID) {
                        wConfiguration.DMSDeviceBOMList.add(wDeviceBOM);
                    }
                }
                //将wMaintenanceRuleResult数据根据ConfigurationID整合到wConfiguration.MaintenanceRuleList中
                for (DMSMaintenanceRule wMaintenanceRule : wMaintenanceRuleResult) {
                    if (wMaintenanceRule.ConfigurationID == wConfiguration.ID) {
                        wConfiguration.MaintenanceRuleList.add(wMaintenanceRule);
                    }
                }

                if (wConfiguration.ParentID == 0) {
                    wResult.Result.add(wConfiguration);
                    continue;
                }
                for (DMSConfiguration wConfiguration1 : wResult.Result) {
                    if (wConfiguration1.ID == wConfiguration.ParentID) {
                        wConfiguration1.DMSConfigurationList.add(wConfiguration);
                        break;
                    }
                }
            }

        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error("DMS_SelectDeviceConfigurationList", e);
        }
        return wResult;
    }

    @Override
    public ServiceResult<Integer> DRM_InitConfiguration(BMSEmployee wLoginUser) {
        ServiceResult<Integer> wResult = new ServiceResult<>(0);
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.put("Active", 1);
            List<DMSDeviceLedger> dmsDeviceLedgers = mDMSDeviceLedgerService.SelectPOList(wLoginUser, wParams,
                    Pagination.getNewMaxSize(),
                    wErrorCode);
            for (DMSDeviceLedger dmsDeviceLedger : dmsDeviceLedgers) {
                wParams.clear();
                wParams.put("DeviceID", dmsDeviceLedger.ID);
                wParams.put("NameEQ", dmsDeviceLedger.Name);
                DMSConfiguration dmsConfiguration = mDMSConfigurationService.SelectPO(wLoginUser, wParams,
                        wErrorCode);
                if (dmsConfiguration != null && dmsConfiguration.ID > 0) {
                    continue;
                }
                //创建设备构型
                dmsConfiguration = new DMSConfiguration(dmsDeviceLedger.ID);
                dmsConfiguration.ID = 0;
                dmsConfiguration.Code = "";
                dmsConfiguration.Name = dmsDeviceLedger.Name;
                dmsConfiguration.Active = 1;
                dmsConfiguration.setUserInfo(BMSEmployee.SysAdmin);
                mDMSConfigurationService.UpdatePo(wLoginUser, dmsConfiguration, wErrorCode);
            }

            wResult.setFaultCode(ExceptionTypes.getEnumType(wErrorCode.Result).getLabel());
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error("DRM_InitConfiguration", e);
        }
        return wResult;
    }

    @Override
    public ServiceResult<List<DMSConfiguration>> DMS_CopyDeviceConfigurationList(BMSEmployee wLoginUser,
                                                                                 DMSDeviceLedger wLedger,

                                                                                 DMSDeviceLedger wTargetLedger) {
        ServiceResult<List<DMSConfiguration>> wResult = new ServiceResult<List<DMSConfiguration>>();
        wResult.Result = new ArrayList<>();
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);
            ServiceResult<List<DMSConfiguration>> listServiceResult =
                    this.DMS_SelectDeviceConfigurationList(wLoginUser, wLedger.ID);
            if (StringUtils.isNotEmpty(listServiceResult.FaultCode)) {
                wResult.FaultCode += listServiceResult.FaultCode;
                return wResult;
            }
            if (listServiceResult.Result == null || listServiceResult.Result.size() == 0) {
                wResult.FaultCode += "未查询到设备构型信息";
                return wResult;
            }
            ServiceResult<Integer> wServiceResult;
            for (DMSConfiguration dmsConfiguration : listServiceResult.Result) {
                dmsConfiguration.ID = 0;
                dmsConfiguration.setUserInfo(wLoginUser);
                dmsConfiguration.DeviceID = wTargetLedger.ID;
                dmsConfiguration.ParentID = 0;
                dmsConfiguration.AssetInfoID = wTargetLedger.AssetInfoID;
                wServiceResult = this.DMS_UpdateConfiguration(wLoginUser, dmsConfiguration);
                if (StringUtils.isNotEmpty(wServiceResult.FaultCode)) {
                    wResult.FaultCode += wServiceResult.FaultCode;
                    continue;
                }
                wResult.Result.add(dmsConfiguration);
            }

        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error("DMS_CopyDeviceConfigurationList", e);
        }
        return wResult;
    }

    @Override
    public ServiceResult<Integer> DRM_SynchronizDeviceConfigurationName(BMSEmployee wLoginUser,
                                                                        DMSDeviceLedger wDMSDeviceLedger) {
        ServiceResult<Integer> wResult = new ServiceResult<>(0);
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.put("DeviceID", wDMSDeviceLedger.ID);
            wParams.put("Active", 1);
            DMSConfiguration dmsConfiguration = mDMSConfigurationService.SelectPO(wLoginUser, wParams,
                    wErrorCode);
            if (dmsConfiguration != null && dmsConfiguration.ID > 0 && !dmsConfiguration.Name.equals(wDMSDeviceLedger.Name)) {
                dmsConfiguration.Name = wDMSDeviceLedger.Name;
                dmsConfiguration.setUserInfo(wLoginUser);
                dmsConfiguration.EditTime = Calendar.getInstance();
                mDMSConfigurationService.UpdatePo(wLoginUser, dmsConfiguration, wErrorCode);
            }

            wResult.setFaultCode(ExceptionTypes.getEnumType(wErrorCode.Result).getLabel());
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error(e.toString());
        }
        return wResult;
    }

    //endregion

    //region 设备维保/点检

    @Override
    public ServiceResult<List<DMSMaintenanceItem>> DMS_QueryMaintenanceItemByRule(BMSEmployee wLoginUser, int wRuleID,
                                                                                  Pagination wPagination) {
        ServiceResult<List<DMSMaintenanceItem>> wResult = new ServiceResult<>();
        wResult.Result = new ArrayList<>();
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.put("MaintenanceRuleID", wRuleID);
            List<DMSMaintenanceRuleItem> dmsMaintenanceRuleItems =
                    mDMSMaintenanceRuleItemPoService.SelectPOList(wLoginUser, wParams, Pagination.getMaxSize(),
                            wErrorCode);
            if (dmsMaintenanceRuleItems.size() > 0) {
                List<Integer> wItemIDList =
                        dmsMaintenanceRuleItems.stream().map(p -> p.MaintenanceItemID).collect(Collectors.toList());
                Map<String, Object> wParams1 = new HashMap<String, Object>();
                wResult.Result = DMSMaintenanceItemDAO.getInstance().SelectPOList(wLoginUser, wItemIDList, null,
                        wParams1,
                        wPagination, wErrorCode);
            }

            wResult.AddFaultCode(wErrorCode);
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error(e.toString());
        }
        return wResult;
    }

    @Override
    public ServiceResult<List<DMSMaintenanceItemTask>> DMS_QueryMaintenanceItemTaskByDevice(BMSEmployee wLoginUser,
                                                                                            int wDeviceID,
                                                                                            int wConfigurationID,
                                                                                            String wName, int wStatus
            , int wType, int wMaintenanceLevel, Pagination wPagination) {
        ServiceResult<List<DMSMaintenanceItemTask>> wResult = new ServiceResult<>();
        wResult.Result = new ArrayList<>();
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            Map<String, Object> wParams = new HashMap<String, Object>();

            List<DMSMaintenanceItem> wDMSMaintenanceItemList = new ArrayList<>();
            switch (DMSItemTaskStatus.getEnumType(wStatus)) {
                case Default:
                    wParams = new HashMap<>();
                    wParams.put("DeviceID", wDeviceID);
                    wParams.put("ConfigurationID", wConfigurationID);
                    wParams.put("Name", wName);
                    wParams.put("Active", 1);
                    wParams.put("Type", wType);
                    wParams.put("MaintenanceLevel", wMaintenanceLevel);

                    wDMSMaintenanceItemList = DMSMaintenanceItemDAO.getInstance().SelectPOList(wLoginUser, wParams,
                            wPagination, wErrorCode);
                    break;
                case ToDispatch:
                case ToRepair:
                case ToCheck:
                case Checked:
                    wDMSMaintenanceItemList =
                            DMSMaintenanceItemDAO.getInstance().DMS_QueryMaintenanceItemListByStatus(
                                    wDeviceID,
                                    wConfigurationID, wName, wStatus, wType, wMaintenanceLevel, wPagination,
                                    wErrorCode);
                    break;
                case NoTask:
                    wDMSMaintenanceItemList =
                            DMSMaintenanceItemDAO.getInstance().DMS_QueryMaintenanceItemListNoTask(wDeviceID,
                                    wConfigurationID, wName, wType, wMaintenanceLevel, wPagination, wErrorCode);
                    break;
                default:
                    break;
            }

            //查询所有今日的设备项点任务和未完成的项点任务
            List<DMSMaintenanceItemTask> wDMSMaintenanceItemTaskList =
                    DMSMaintenanceItemTaskDAO.getInstance().DMS_QueryToDayTaskList(wLoginUser, wType, wErrorCode);

            Calendar wBaseTime1 = Calendar.getInstance();
            wBaseTime1.set(2000, 0, 1, 0, 0, 0);

            Calendar wBaseTime2 = Calendar.getInstance();
            wBaseTime2.set(2010, 0, 1, 0, 0, 0);

            SimpleDateFormat wSDF = new SimpleDateFormat("yyyy-MM-dd");

            DMSMaintenanceItemTask wTask;
            for (DMSMaintenanceItem wDMSMaintenanceItem : wDMSMaintenanceItemList) {
                wTask = new DMSMaintenanceItemTask();
                if (wDMSMaintenanceItemTaskList.stream().anyMatch(p -> p.MaintenanceItemID == wDMSMaintenanceItem.ID)) {
                    List<DMSMaintenanceItemTask> wTaskList =
                            wDMSMaintenanceItemTaskList.stream().filter(p -> p.MaintenanceItemID == wDMSMaintenanceItem.ID).collect(Collectors.toList());
                    wTask = wTaskList.stream().max(Comparator.comparing(DMSMaintenanceItemTask::getEditTime)).get();
                    wTask.DeviceID = wDMSMaintenanceItem.DeviceID;
                    wTask.DeviceName = wDMSMaintenanceItem.DeviceName;
                    wTask.ConfigurationID = wDMSMaintenanceItem.ConfigurationID;
                    wTask.ConfigurationName = wDMSMaintenanceItem.ConfigurationName;
                    wTask.MaintenanceItemID = wDMSMaintenanceItem.ID;
                    wTask.MaintenanceItemName = wDMSMaintenanceItem.Name;
                    wTask.MaintenanceItemDescription = wDMSMaintenanceItem.Description;
                    wTask.CreateTimeText = wSDF.format(wTask.CreateTime.getTime());
                    wTask.WorkerTimeText = wTask.WorkerTime.compareTo(wBaseTime2) > 0 ?
                            wSDF.format(wTask.WorkerTime.getTime()) : "-";
                    if (wTask.WorkerID <= 0) {
                        wTask.WorkerTimeText = "-";
                    }
                    wTask.ResultText = wTask.Result == 1 ? "合格" : wTask.Result == 2 ? "不合格" : "未保养";
                    wTask.StatusText = Objects.requireNonNull(DMSItemTaskStatus.getEnumType(wTask.Status)).getLabel();
                    wTask.Type = wTask.Result == 1 ? "success" : wTask.Result == 2 ? "danger" : "info";
                    wTask.StatusType = wTask.Status == 4 ? "success" : "warning";
                } else {
                    wTask.DeviceID = wDMSMaintenanceItem.DeviceID;
                    wTask.DeviceName = wDMSMaintenanceItem.DeviceName;
                    wTask.ConfigurationID = wDMSMaintenanceItem.ConfigurationID;
                    wTask.ConfigurationName = wDMSMaintenanceItem.ConfigurationName;
                    wTask.MaintenanceItemID = wDMSMaintenanceItem.ID;
                    wTask.MaintenanceItemName = wDMSMaintenanceItem.Name;
                    wTask.MaintenanceItemDescription = wDMSMaintenanceItem.Description;
                    wTask.MaintenanceLevel = wMaintenanceLevel;
                    wTask.MaintenanceLevelText = DMSMaintenanceLevel.getEnumType(wMaintenanceLevel).getLabel();
                    wTask.CreateTimeText = "-";
                    wTask.WorkerTimeText = "-";
                    wTask.DispatchTime = wBaseTime1;
                    wTask.CheckerTime = wBaseTime1;
                    wTask.ResultText = "未保养";
                    wTask.StatusText = "无任务";
                    wTask.Type = "info";
                    wTask.StatusType = "info";
                }
                wTask.MaintenanceItemType = wType;
                wTask.LastMaintenanceTime = wDMSMaintenanceItem.LastMaintenanceTime.compareTo(wBaseTime2) > 0 ?
                        wSDF.format(wDMSMaintenanceItem.LastMaintenanceTime.getTime()) : "-";
                wTask.LoginID = wLoginUser.ID;
                wResult.Result.add(wTask);
            }

            wResult.AddFaultCode(wErrorCode);
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error(e.toString());
        }
        return wResult;
    }

    @Override
    public ServiceResult<Integer> DMS_TriggerTaskMaintenanceItem(BMSEmployee wLoginUser,
                                                                 List<DMSMaintenanceItemTask> wDMSMaintenanceItemTaskList, int wType) {
        ServiceResult<Integer> wResult = new ServiceResult<>(0);
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            //查询所有今日的设备维修任务和未完成的设备任务
            List<DMSMaintenanceTask> wDMSMaintenanceTaskList =
                    DMSMaintenanceTaskDAO.getInstance().DMS_QueryToDayTaskList(wLoginUser, wType, wErrorCode);
            //查询今日任务
            List<DMSMaintenanceItemTask> wTodayTaskList =
                    DMSMaintenanceItemTaskDAO.getInstance().DMS_QueryToDayTaskList(wLoginUser, wType, wErrorCode);

            for (DMSMaintenanceItemTask wDMSMaintenanceItemTask : wDMSMaintenanceItemTaskList) {
                if (wTodayTaskList.stream().anyMatch(p -> p.MaintenanceItemID == wDMSMaintenanceItemTask.MaintenanceItemID))
                    continue;

                wDMSMaintenanceItemTask.ID = 0;
                wDMSMaintenanceItemTask.CreatorID = wLoginUser.ID;
                wDMSMaintenanceItemTask.CreateTime = Calendar.getInstance();
                wDMSMaintenanceItemTask.EditorID = wLoginUser.ID;
                wDMSMaintenanceItemTask.EditTime = Calendar.getInstance();
                wDMSMaintenanceItemTask.Status = DMSItemTaskStatus.ToDispatch.getValue();
                wDMSMaintenanceItemTask.PlanDate = Calendar.getInstance();

                mDMSMaintenanceItemTaskService.UpdatePo(wLoginUser, wDMSMaintenanceItemTask, wErrorCode);

                //触发设备任务，若没有的话
                if (wDMSMaintenanceTaskList.stream().noneMatch(p -> p.DeviceID == wDMSMaintenanceItemTask.DeviceID)) {
                    DMSMaintenanceTask wDMSMaintenanceTask = new DMSMaintenanceTask();
                    wDMSMaintenanceTask.ID = 0;
                    wDMSMaintenanceTask.CreatorID = wLoginUser.ID;
                    wDMSMaintenanceTask.CreateTime = Calendar.getInstance();
                    wDMSMaintenanceTask.EditorID = wLoginUser.ID;
                    wDMSMaintenanceTask.EditTime = Calendar.getInstance();
                    wDMSMaintenanceTask.DeviceID = wDMSMaintenanceItemTask.DeviceID;
                    wDMSMaintenanceTask.Status = 1;

                    mDMSMaintenanceTaskService.UpdatePo(wLoginUser, wDMSMaintenanceTask,
                            wErrorCode);

                    //维护任务ID
                    if (wDMSMaintenanceItemTask.ID > 0 && wDMSMaintenanceTask.ID > 0) {
                        wDMSMaintenanceItemTask.TaskID = wDMSMaintenanceTask.ID;
                        mDMSMaintenanceItemTaskService.UpdatePo(wLoginUser, wDMSMaintenanceItemTask,
                                wErrorCode);
                    }
                } else {
                    if (wDMSMaintenanceItemTask.ID > 0) {
                        wDMSMaintenanceItemTask.TaskID =
                                wDMSMaintenanceTaskList.stream().filter(p -> p.DeviceID == wDMSMaintenanceItemTask.DeviceID).max(Comparator.comparing(DMSMaintenanceTask::getID)).get().ID;
                        mDMSMaintenanceItemTaskService.UpdatePo(wLoginUser, wDMSMaintenanceItemTask,
                                wErrorCode);
                        //更新最新主单据的状态为待维保
                        Map<String, Object> wParams = new HashMap<String, Object>();
                        wParams.put("ID", wDMSMaintenanceItemTask.TaskID);
                        DMSMaintenanceTask dmsMaintenanceTask = mDMSMaintenanceTaskService.SelectPO(wLoginUser,
                                wParams, wErrorCode);
                        if (dmsMaintenanceTask != null && dmsMaintenanceTask.ID > 0) {
                            dmsMaintenanceTask.Status = 1;
                            dmsMaintenanceTask.EditorID = wLoginUser.ID;
                            dmsMaintenanceTask.EditTime = Calendar.getInstance();
                            mDMSMaintenanceTaskService.UpdatePo(wLoginUser, dmsMaintenanceTask, wErrorCode);
                        }
                    }
                }
            }

            wResult.AddFaultCode(wErrorCode);
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error(e.toString());
        }
        return wResult;
    }

    @Override
    public ServiceResult<Integer> DMS_SubmitMaintenanceItemTask(BMSEmployee wLoginUser,
                                                                DMSMaintenanceItemTask wDMSMaintenanceItemTask,
                                                                int wType) {
        ServiceResult<Integer> wResult = new ServiceResult<>(0);
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            Map<String, Object> wParams = new HashMap<String, Object>();
            DMSItemTaskStatus wDMSItemTaskStatus = DMSItemTaskStatus.getEnumType(wType);
            switch (wDMSItemTaskStatus) {
                case ToDispatch: {
                    wDMSMaintenanceItemTask.DispatchPersonID = wLoginUser.ID;
                    wDMSMaintenanceItemTask.DispatchTime = Calendar.getInstance();
                    wDMSMaintenanceItemTask.Status = DMSItemTaskStatus.ToRepair.getValue();
                    //和荣专用
                    wDMSMaintenanceItemTask.WorkerID = wLoginUser.ID;
                    wDMSMaintenanceItemTask.WorkerTime = Calendar.getInstance();
                    //维护上次保养时间
                    wParams.put("ID", wDMSMaintenanceItemTask.MaintenanceItemID);
                    DMSMaintenanceItem dmsMaintenanceItem = DMSMaintenanceItemDAO.getInstance().SelectPO(wLoginUser,
                            wParams
                            , wErrorCode);
                    if (dmsMaintenanceItem != null && dmsMaintenanceItem.ID > 0) {
                        dmsMaintenanceItem.LastMaintenanceTime = Calendar.getInstance();
                        DMSMaintenanceItemDAO.getInstance().UpdatePo(wLoginUser, dmsMaintenanceItem, wErrorCode);
                    }
                }
                break;
                case ToRepair: {
                    wDMSMaintenanceItemTask.WorkerID = wLoginUser.ID;
                    wDMSMaintenanceItemTask.WorkerTime = Calendar.getInstance();
                    wDMSMaintenanceItemTask.Status = DMSItemTaskStatus.ToCheck.getValue();
                    //维护上次保养时间
                    wParams.put("ID", wDMSMaintenanceItemTask.MaintenanceItemID);
                    DMSMaintenanceItem dmsMaintenanceItem = DMSMaintenanceItemDAO.getInstance().SelectPO(wLoginUser,
                            wParams
                            , wErrorCode);
                    if (dmsMaintenanceItem != null && dmsMaintenanceItem.ID > 0) {
                        dmsMaintenanceItem.LastMaintenanceTime = Calendar.getInstance();
                        DMSMaintenanceItemDAO.getInstance().UpdatePo(wLoginUser, dmsMaintenanceItem, wErrorCode);
                    }
                }

                break;
                case ToCheck:
                    wDMSMaintenanceItemTask.CheckerID = wLoginUser.ID;
                    wDMSMaintenanceItemTask.CheckerTime = Calendar.getInstance();
                    wDMSMaintenanceItemTask.Status = DMSItemTaskStatus.Checked.getValue();
                    break;
                default:
                    break;
            }
            wDMSMaintenanceItemTask.EditorID = wLoginUser.ID;
            wDMSMaintenanceItemTask.EditTime = Calendar.getInstance();
            wResult.Result = mDMSMaintenanceItemTaskService.UpdatePo(wLoginUser, wDMSMaintenanceItemTask,
                    wErrorCode);

            //维护主任务的状态
            if (wDMSMaintenanceItemTask.TaskID > 0 && wDMSMaintenanceItemTask.Status == DMSItemTaskStatus.ToRepair.getValue()) {

                DMSMaintenanceItemRecord wMaintenanceItemRecord = new DMSMaintenanceItemRecord
                        (wDMSMaintenanceItemTask);

                DMSMaintenanceItemRecordDAO.getInstance().UpdatePo(wLoginUser, wMaintenanceItemRecord
                        , wErrorCode);

                wParams = new HashMap<>();
                wParams.put("TaskID", wDMSMaintenanceItemTask.TaskID);
                List<DMSMaintenanceItemTask> wList = mDMSMaintenanceItemTaskService.SelectPOList(wLoginUser,
                        wParams, Pagination.getMaxSize(), wErrorCode);

                if (wList != null && wList.size() > 0
                        && wList.stream().allMatch(p -> p.Status == DMSItemTaskStatus.ToRepair.getValue())) {
                    wParams.clear();
                    wParams.put("ID", wDMSMaintenanceItemTask.TaskID);
                    DMSMaintenanceTask dmsMaintenanceTask = mDMSMaintenanceTaskService.SelectPO(wLoginUser,
                            wParams
                            , wErrorCode);
                    if (dmsMaintenanceTask != null && dmsMaintenanceTask.ID > 0) {
                        dmsMaintenanceTask.Status = 2;
                        dmsMaintenanceTask.EditorID = wLoginUser.ID;
                        dmsMaintenanceTask.EditTime = Calendar.getInstance();
                        mDMSMaintenanceTaskService.UpdatePo(wLoginUser, dmsMaintenanceTask, wErrorCode);
                    }
                }
            }

            //设备点检完成后消除工位报警
            ClearStationAlarm(wLoginUser, wDMSMaintenanceItemTask, wErrorCode);

            wResult.AddFaultCode(wErrorCode);
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error(e.toString());
        }
        return wResult;
    }

    /**
     * 消除工位报警
     */
    private void ClearStationAlarm(BMSEmployee wLoginUser, DMSMaintenanceItemTask wDMSMaintenanceItemTask,
                                   OutResult<Integer> wErrorCode) {
        try {
            //①查询进度
            List<DMSMaintenancePlan> wDMSMaintenancePlanList =
                    DRMServiceImpl.getInstance().DMS_QueryDMSMaintenancePlanList(wLoginUser
                            , wDMSMaintenanceItemTask.DeviceCode, "", 0, -1,
                            -1, -1, 1, Pagination.getNewMaxSize()).Result;
            if (wDMSMaintenancePlanList != null && wDMSMaintenancePlanList.size() > 0
                    && wDMSMaintenancePlanList.get(0).ID == wDMSMaintenanceItemTask.DeviceID) {
                if (wDMSMaintenancePlanList.get(0).Total == wDMSMaintenancePlanList.get(0).FQTY && wDMSMaintenancePlanList.get(0).FQTY > 0) {
                    //②查询工位
                    Map<String, Object> wParams = new HashMap<String, Object>();
                    wParams.put("DeviceID", wDMSMaintenanceItemTask.DeviceID);
                    List<FMCStation> fmcStations = mFMCStationService.SelectPOList(wLoginUser, wParams,
                            Pagination.getNewMaxSize(),
                            wErrorCode);
                    for (FMCStation fmcStation : fmcStations) {
                        //③更新工位报警状态
                        if (fmcStation.Status == 1) {
                            fmcStation.Status = 0;
                            fmcStation.AlarmText = "";
                            mFMCStationService.UpdatePo(wLoginUser, fmcStation, wErrorCode);
                        }
                    }

                }
            }
        } catch (Exception ex) {
            logger.error("ClearStationAlarm", ex);
        }
    }

    @Override
    public ServiceResult<List<DMSMaintenanceRule>> DMS_QueryMaintenanceRuleByMaintenanceItemID(BMSEmployee wLoginUser
            , int wMaintenanceItemID, int wType, String wDescription, int wActive, Pagination wPagination) {
        ServiceResult<List<DMSMaintenanceRule>> wResult = new ServiceResult<>();
        wResult.Result = new ArrayList<>();
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            if (wType <= 0) {
                wType = -1;
            }

            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.put("MaintenanceItemID", wMaintenanceItemID);

            List<DMSMaintenanceRuleItem> dmsMaintenanceRuleItems =
                    mDMSMaintenanceRuleItemPoService.SelectPOList(wLoginUser, wParams, Pagination.getMaxSize(),
                            wErrorCode);
            if (dmsMaintenanceRuleItems != null && dmsMaintenanceRuleItems.size() > 0) {
                List<Integer> wRuleIDList =
                        dmsMaintenanceRuleItems.stream().map(p -> p.MaintenanceRuleID).distinct().collect(Collectors.toList());

                wParams = new HashMap<>();
                wParams.put("Type", wType);
                wParams.put("Description", wDescription);
                wParams.put("Active", wActive);

                wResult.Result = mDMSMaintenanceRulePoService.SelectPOList(wLoginUser, wRuleIDList, wParams,
                        wPagination, wErrorCode);
            }

            wResult.AddFaultCode(wErrorCode);
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error(e.toString());
        }
        return wResult;
    }

    @Override
    public ServiceResult<List<DMSMaintenancePlan>> DMS_QueryDMSMaintenancePlanList(BMSEmployee wLoginUser,
                                                                                   String wCode, String wName,
                                                                                   int wStatus,
                                                                                   int wFactoryID, int wWorkShopID,
                                                                                   int wWorkAreaID,
                                                                                   int wType, Pagination wPagination) {
        ServiceResult<List<DMSMaintenancePlan>> wResult = new ServiceResult<>();
        wResult.Result = new ArrayList<>();
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            //分页查询所有设备
            List<DMSDeviceLedger> wList = new ArrayList<>();

            switch (wStatus) {
                case 0:
                    wList = DMSMaintenanceTaskDAO.getInstance().DMS_SelectDeviceLedgerList(wLoginUser,
                            wCode, wName, wFactoryID, wWorkShopID, wWorkAreaID, wPagination, wErrorCode);
                    break;
                case 1:
                    wList = DMSMaintenanceTaskDAO.getInstance().DMS_SelectDeviceLedgerListToRepair(wLoginUser,
                            wCode, wName, wFactoryID, wWorkShopID, wWorkAreaID, wPagination, wErrorCode);
                    break;
                case 2:
                    wList = DMSMaintenanceTaskDAO.getInstance().DMS_SelectDeviceLedgerListRepaired(wLoginUser,
                            wCode, wName, wFactoryID, wWorkShopID, wWorkAreaID, wPagination, wErrorCode);
                    break;
                case 3:
                    wList = DMSMaintenanceTaskDAO.getInstance().DMS_SelectDeviceLedgerListNotRepair(wLoginUser,
                            wCode, wName, wFactoryID, wWorkShopID, wWorkAreaID, wPagination, wErrorCode);
                    break;
                default:
                    break;
            }

            //查询所有今日的设备维修任务和未完成的设备任务
            List<DMSMaintenanceTask> wDMSMaintenanceTaskList =
                    DMSMaintenanceTaskDAO.getInstance().DMS_QueryToDayTaskList(wLoginUser, wType, wErrorCode);
            //查询所有今日的设备项点任务和未完成的项点任务
            List<DMSMaintenanceItemTask> wDMSMaintenanceItemTaskList =
                    DMSMaintenanceItemTaskDAO.getInstance().DMS_QueryToDayTaskList(wLoginUser, wType, wErrorCode);
            //根据设备ID查询所有已完成的维修任务
            List<Integer> wDeviceIDList = wList.stream().map(p -> p.ID).distinct().collect(Collectors.toList());

            List<DMSMaintenanceItemTask> wTimeTask =
                    DMSMaintenanceItemTaskDAO.getInstance().DMS_QueryListByDeviceIDList(wLoginUser, wDeviceIDList,
                            wType,
                            wErrorCode);

            SimpleDateFormat wSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (DMSDeviceLedger wDMSDeviceLedger : wList) {
                DMSMaintenancePlan wDMSMaintenancePlan = new DMSMaintenancePlan();
                wDMSMaintenancePlan.ID = wDMSDeviceLedger.ID;
                wDMSMaintenancePlan.Code = wDMSDeviceLedger.Code;
                wDMSMaintenancePlan.Name = wDMSDeviceLedger.Name;
                if (wTimeTask.stream().anyMatch(p -> p.DeviceID == wDMSDeviceLedger.ID)) {
                    Calendar wMaxTime =
                            wTimeTask.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID).max(Comparator.comparing(DMSMaintenanceItemTask::getEditTime)).get().EditTime;
                    wDMSMaintenancePlan.LastRepairTime = wSDF.format(wMaxTime.getTime());
                } else
                    wDMSMaintenancePlan.LastRepairTime = "-";


                UpdateDayMaintanince(wType, wDMSMaintenanceTaskList,
                        wDMSMaintenanceItemTaskList.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID && p.MaintenanceLevel
                                == DMSMaintenanceLevel.Daily.getValue()).collect(Collectors.toList()), wDMSDeviceLedger,
                        wDMSMaintenancePlan);
                UpdateOneMaintanince(wType, wDMSMaintenanceTaskList,
                        wDMSMaintenanceItemTaskList.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID && p.MaintenanceLevel
                                == DMSMaintenanceLevel.OneLevel.getValue()).collect(Collectors.toList()),
                        wDMSDeviceLedger,
                        wDMSMaintenancePlan);
                UpdateTwoMaintanince(wType, wDMSMaintenanceTaskList,
                        wDMSMaintenanceItemTaskList.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID && p.MaintenanceLevel
                                == DMSMaintenanceLevel.TwoLevel.getValue()).collect(Collectors.toList()),
                        wDMSDeviceLedger,
                        wDMSMaintenancePlan);
                wResult.Result.add(wDMSMaintenancePlan);
            }


            wResult.AddFaultCode(wErrorCode);
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error(e.toString());
        }
        return wResult;
    }

    /**
     * 日常保养数据维护
     */
    private void UpdateDayMaintanince(int wType, List<DMSMaintenanceTask> wDMSMaintenanceTaskList,
                                      List<DMSMaintenanceItemTask> wDMSMaintenanceItemTaskList,
                                      DMSDeviceLedger wDMSDeviceLedger
            , DMSMaintenancePlan wDMSMaintenancePlan) {
        try {
            if (wDMSMaintenanceItemTaskList.stream().anyMatch(p -> p.DeviceID == wDMSDeviceLedger.ID
                    && p.Status == DMSItemTaskStatus.ToDispatch.getValue()
                    && p.MaintenanceLevel == DMSMaintenanceLevel.Daily.getValue())) {
                wDMSMaintenancePlan.Status = 1;
                wDMSMaintenancePlan.StatusText = "待点检";
                if (wType == 2) {
                    wDMSMaintenancePlan.StatusText = "待点检";
                }
                wDMSMaintenancePlan.Type = "danger";
                if (wDMSMaintenanceItemTaskList.stream().anyMatch(p -> p.DeviceID == wDMSDeviceLedger.ID)) {
                    wDMSMaintenancePlan.Total =
                            (int) wDMSMaintenanceItemTaskList.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID && p.MaintenanceLevel == DMSMaintenanceLevel.Daily.getValue()).count();
                    wDMSMaintenancePlan.FQTY =
                            (int) wDMSMaintenanceItemTaskList.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID
                                    && p.Status == DMSItemTaskStatus.ToRepair.getValue() && p.MaintenanceLevel == DMSMaintenanceLevel.Daily.getValue()).count();
                    wDMSMaintenancePlan.Percent =
                            (int) (((double) wDMSMaintenancePlan.FQTY / wDMSMaintenancePlan.Total) * 100);
                }
            } else if (wDMSMaintenanceItemTaskList.size() > 0 && wDMSMaintenanceItemTaskList.stream().allMatch(p -> p.DeviceID == wDMSDeviceLedger.ID
                    && p.Status == DMSItemTaskStatus.ToRepair.getValue()
                    && p.MaintenanceLevel == DMSMaintenanceLevel.Daily.getValue())) {
                wDMSMaintenancePlan.Status = 2;
                wDMSMaintenancePlan.StatusText = "已点检";
                if (wType == 2) {
                    wDMSMaintenancePlan.StatusText = "已点检";
                }
                wDMSMaintenancePlan.Type = "success";
                wDMSMaintenancePlan.Total =
                        (int) wDMSMaintenanceItemTaskList.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID && p.MaintenanceLevel == DMSMaintenanceLevel.Daily.getValue()).count();
                wDMSMaintenancePlan.FQTY =
                        (int) wDMSMaintenanceItemTaskList.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID
                                && p.Status == DMSItemTaskStatus.ToRepair.getValue() && p.MaintenanceLevel == DMSMaintenanceLevel.Daily.getValue()).count();
                wDMSMaintenancePlan.Percent =
                        (int) (((double) wDMSMaintenancePlan.FQTY / wDMSMaintenancePlan.Total) * 100);
            } else {
                wDMSMaintenancePlan.Status = 3;
                wDMSMaintenancePlan.StatusText = "不点检";
                if (wType == 2) {
                    wDMSMaintenancePlan.StatusText = "不点检";
                }
                wDMSMaintenancePlan.Type = "info";
                wDMSMaintenancePlan.Percent = 0;
                wDMSMaintenancePlan.FQTY = 0;
                wDMSMaintenancePlan.Total = 0;
            }
        } catch (Exception ex) {
            logger.error("UpdateDayMaintanince", ex);
        }

    }

    /**
     * 日常保养数据维护
     */
    private void UpdateOneMaintanince(int wType, List<DMSMaintenanceTask> wDMSMaintenanceTaskList,
                                      List<DMSMaintenanceItemTask> wDMSMaintenanceItemTaskList,
                                      DMSDeviceLedger wDMSDeviceLedger
            , DMSMaintenancePlan wDMSMaintenancePlan) {
        try {
            if (wDMSMaintenanceItemTaskList.stream().anyMatch(p -> p.DeviceID == wDMSDeviceLedger.ID
                    && p.Status == DMSItemTaskStatus.ToDispatch.getValue()
                    && p.MaintenanceLevel == DMSMaintenanceLevel.OneLevel.getValue())) {
                wDMSMaintenancePlan.Status_One = 1;
                wDMSMaintenancePlan.StatusText_One = "待点检";
                if (wType == 2) {
                    wDMSMaintenancePlan.StatusText_One = "待点检";
                }
                wDMSMaintenancePlan.Type_One = "danger";
                if (wDMSMaintenanceItemTaskList.stream().anyMatch(p -> p.DeviceID == wDMSDeviceLedger.ID)) {
                    wDMSMaintenancePlan.Total_One =
                            (int) wDMSMaintenanceItemTaskList.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID && p.MaintenanceLevel == DMSMaintenanceLevel.OneLevel.getValue()).count();
                    wDMSMaintenancePlan.FQTY_One =
                            (int) wDMSMaintenanceItemTaskList.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID
                                    && p.Status == DMSItemTaskStatus.ToRepair.getValue() && p.MaintenanceLevel == DMSMaintenanceLevel.OneLevel.getValue()).count();
                    wDMSMaintenancePlan.Percent =
                            (int) (((double) wDMSMaintenancePlan.FQTY / wDMSMaintenancePlan.Total) * 100);
                }
            } else if (wDMSMaintenanceItemTaskList.size() > 0 && wDMSMaintenanceItemTaskList.stream().allMatch(p -> p.DeviceID == wDMSDeviceLedger.ID
                    && p.Status == DMSItemTaskStatus.ToRepair.getValue()
                    && p.MaintenanceLevel == DMSMaintenanceLevel.OneLevel.getValue())) {
                wDMSMaintenancePlan.Status_One = 2;
                wDMSMaintenancePlan.StatusText_One = "已点检";
                if (wType == 2) {
                    wDMSMaintenancePlan.StatusText_One = "已点检";
                }
                wDMSMaintenancePlan.Type_One = "success";
                wDMSMaintenancePlan.Total_One =
                        (int) wDMSMaintenanceItemTaskList.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID && p.MaintenanceLevel == DMSMaintenanceLevel.OneLevel.getValue()).count();
                wDMSMaintenancePlan.FQTY_One =
                        (int) wDMSMaintenanceItemTaskList.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID
                                && p.Status == DMSItemTaskStatus.ToRepair.getValue() && p.MaintenanceLevel == DMSMaintenanceLevel.OneLevel.getValue()).count();
                wDMSMaintenancePlan.Percent =
                        (int) (((double) wDMSMaintenancePlan.FQTY / wDMSMaintenancePlan.Total) * 100);
            } else {
                wDMSMaintenancePlan.Status_One = 3;
                wDMSMaintenancePlan.StatusText_One = "不点检";
                if (wType == 2) {
                    wDMSMaintenancePlan.StatusText_One = "不点检";
                }
                wDMSMaintenancePlan.Type_One = "info";
                wDMSMaintenancePlan.Percent = 0;
                wDMSMaintenancePlan.FQTY_One = 0;
                wDMSMaintenancePlan.Total_One = 0;
            }
        } catch (Exception ex) {
            logger.error("UpdateOneMaintanince", ex);
        }

    }

    /**
     * 日常保养数据维护
     */
    private void UpdateTwoMaintanince(int wType, List<DMSMaintenanceTask> wDMSMaintenanceTaskList,
                                      List<DMSMaintenanceItemTask> wDMSMaintenanceItemTaskList,
                                      DMSDeviceLedger wDMSDeviceLedger
            , DMSMaintenancePlan wDMSMaintenancePlan) {
        try {
            if (wDMSMaintenanceItemTaskList.stream().anyMatch(p -> p.DeviceID == wDMSDeviceLedger.ID
                    && p.Status == DMSItemTaskStatus.ToDispatch.getValue()
                    && p.MaintenanceLevel == DMSMaintenanceLevel.TwoLevel.getValue())) {
                wDMSMaintenancePlan.Status_Two = 1;
                wDMSMaintenancePlan.StatusText_Two = "待点检";
                if (wType == 2) {
                    wDMSMaintenancePlan.StatusText_Two = "待点检";
                }
                wDMSMaintenancePlan.Type_Two = "danger";
                if (wDMSMaintenanceItemTaskList.stream().anyMatch(p -> p.DeviceID == wDMSDeviceLedger.ID)) {
                    wDMSMaintenancePlan.Total_Two =
                            (int) wDMSMaintenanceItemTaskList.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID && p.MaintenanceLevel == DMSMaintenanceLevel.TwoLevel.getValue()).count();
                    wDMSMaintenancePlan.FQTY_Two =
                            (int) wDMSMaintenanceItemTaskList.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID
                                    && p.Status == DMSItemTaskStatus.ToRepair.getValue() && p.MaintenanceLevel == DMSMaintenanceLevel.TwoLevel.getValue()).count();
                    wDMSMaintenancePlan.Percent =
                            (int) (((double) wDMSMaintenancePlan.FQTY / wDMSMaintenancePlan.Total) * 100);
                }
            } else if (wDMSMaintenanceItemTaskList.size() > 0 && wDMSMaintenanceItemTaskList.stream().allMatch(p -> p.DeviceID == wDMSDeviceLedger.ID
                    && p.Status == DMSItemTaskStatus.ToRepair.getValue()
                    && p.MaintenanceLevel == DMSMaintenanceLevel.TwoLevel.getValue())) {
                wDMSMaintenancePlan.Status_Two = 2;
                wDMSMaintenancePlan.StatusText_Two = "已点检";
                if (wType == 2) {
                    wDMSMaintenancePlan.StatusText_Two = "已点检";
                }
                wDMSMaintenancePlan.Type_Two = "success";
                wDMSMaintenancePlan.Total_Two =
                        (int) wDMSMaintenanceItemTaskList.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID && p.MaintenanceLevel == DMSMaintenanceLevel.TwoLevel.getValue()).count();
                wDMSMaintenancePlan.FQTY_Two =
                        (int) wDMSMaintenanceItemTaskList.stream().filter(p -> p.DeviceID == wDMSDeviceLedger.ID
                                && p.Status == DMSItemTaskStatus.ToRepair.getValue() && p.MaintenanceLevel == DMSMaintenanceLevel.TwoLevel.getValue()).count();
                wDMSMaintenancePlan.Percent =
                        (int) (((double) wDMSMaintenancePlan.FQTY / wDMSMaintenancePlan.Total) * 100);
            } else {
                wDMSMaintenancePlan.Status_Two = 3;
                wDMSMaintenancePlan.StatusText_Two = "不点检";
                if (wType == 2) {
                    wDMSMaintenancePlan.StatusText_Two = "不点检";
                }
                wDMSMaintenancePlan.Type_Two = "info";
                wDMSMaintenancePlan.Percent = 0;
                wDMSMaintenancePlan.FQTY_Two = 0;
                wDMSMaintenancePlan.Total_Two = 0;
            }
        } catch (Exception ex) {
            logger.error("UpdateDayMaintanince", ex);
        }

    }

    @Override
    public ServiceResult<Integer> DMS_UpdateMaintenanceRule(BMSEmployee wLoginUser,
                                                            DMSMaintenanceRule wDMSMaintenanceRule) {
        ServiceResult<Integer> wResult = new ServiceResult<>(0);
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            //编辑规则，会自动重置下次生效时间
            Calendar wBaseTime = Calendar.getInstance();
            wBaseTime.set(2010, 0, 1, 0, 0, 0);
            if (wDMSMaintenanceRule.EffectiveTime.compareTo(wBaseTime) > 0) {
                wDMSMaintenanceRule.NextWorkTime = Calendar.getInstance();//立即生效
//                wDMSMaintenanceRule.NextWorkTime.add(Calendar.DAY_OF_MONTH, wDMSMaintenanceRule.Times);
            }
            wDMSMaintenanceRule.EditorID = wLoginUser.ID;
            int wNewID = mDMSMaintenanceRulePoService.UpdateCheckPo(wLoginUser, wDMSMaintenanceRule, wErrorCode);
            if (wNewID > 0) {
                DMSMaintenanceRuleItem wDMSMaintenanceRuleItem;
                for (DMSMaintenanceItem dmsMaintenanceItem : wDMSMaintenanceRule.MaintenanceItemList) {
                    wDMSMaintenanceRuleItem = new DMSMaintenanceRuleItem();
                    wDMSMaintenanceRuleItem.ID = 0;
                    wDMSMaintenanceRuleItem.MaintenanceRuleID = wDMSMaintenanceRule.ID;
                    wDMSMaintenanceRuleItem.MaintenanceItemID = dmsMaintenanceItem.ID;
                    mDMSMaintenanceRuleItemPoService.UpdatePo(wLoginUser, wDMSMaintenanceRuleItem, wErrorCode);
                }
            }

            wResult.AddFaultCode(wErrorCode);
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error(e.toString());
        }
        return wResult;
    }

    @Override
    public ServiceResult<List<DMSMaintenanceStep>> DMS_QueryMaintenanceStepAll(BMSEmployee wLoginUser, Map<String,
            Object> wParams, Pagination wPagination) {
        ServiceResult<List<DMSMaintenanceStep>> wResult = new ServiceResult<>();
        wResult.Result = new ArrayList<>();
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            wResult.Result = mDMSMaintenanceStepService.SelectPOList(wLoginUser, wParams, wPagination, wErrorCode);

            if (wResult.Result.size() > 0) {
                Map<String, Object> wParams1 = new HashMap<String, Object>();

                //工装数据
                List<AMSFrockTool> wAMSFrockToolList = mAMSFrockToolService.SelectPOList(wLoginUser, wParams1,
                        Pagination.getMaxSize(), wErrorCode);
                //量器具数据
                List<AMSMeasureTool> wAMSMeasureToolList = mAMSMeasureToolService.SelectPOList(wLoginUser, wParams1,
                        Pagination.getMaxSize(), wErrorCode);
                //资质数据
                List<BMSQualification> wBMSQualificationList = mBMSQualificationService.SelectPOList(wLoginUser,
                        wParams1,
                        Pagination.getMaxSize(), wErrorCode);

                for (DMSMaintenanceStep wDMSMaintenanceStep : wResult.Result) {
                    //翻译工装
                    if (wDMSMaintenanceStep.FrockToolList != null && wDMSMaintenanceStep.FrockToolList.size() > 0) {
                        wDMSMaintenanceStep.FrockToolNames = StringUtils.Join(",",
                                wAMSFrockToolList.stream().filter(p -> wDMSMaintenanceStep.FrockToolList.stream().
                                        anyMatch(q -> q == p.ID)).map(p -> p.Name).collect(Collectors.toList()));
                    }
                    //翻译量器具
                    if (wDMSMaintenanceStep.MeasureToolList != null && wDMSMaintenanceStep.MeasureToolList.size() > 0) {
                        wDMSMaintenanceStep.MeasureToolNames = StringUtils.Join(",",
                                wAMSMeasureToolList.stream().filter(p -> wDMSMaintenanceStep.MeasureToolList.stream().
                                        anyMatch(q -> q == p.ID)).map(p -> p.Name).collect(Collectors.toList()));
                    }
                    //翻译资质
                    if (wDMSMaintenanceStep.QualificationsList != null && wDMSMaintenanceStep.QualificationsList.size() > 0) {
                        wDMSMaintenanceStep.QualificationNames = StringUtils.Join(",",
                                wBMSQualificationList.stream().filter(p -> wDMSMaintenanceStep.QualificationsList.stream().
                                        anyMatch(q -> q == p.ID)).map(p -> p.Name).collect(Collectors.toList()));
                    }
                }
            }

            wResult.AddFaultCode(wErrorCode);
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error(e.toString());
        }
        return wResult;
    }

    @Override
    public ServiceResult<DMSMaintenanceStep> DMS_QueryMaintenanceStepInfo(BMSEmployee wLoginUser,
                                                                          Map<String, Object> wParams) {
        ServiceResult<DMSMaintenanceStep> wResult = new ServiceResult<>();
        wResult.Result = new DMSMaintenanceStep();
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            wResult.Result = mDMSMaintenanceStepService.SelectPO(wLoginUser, wParams, wErrorCode);
            if (wResult.Result.ID > 0) {
                Map<String, Object> wParams1 = new HashMap<String, Object>();
                //工装数据
                List<AMSFrockTool> wAMSFrockToolList = mAMSFrockToolService.SelectPOList(wLoginUser, wParams1,
                        Pagination.getMaxSize(), wErrorCode);
                //量器具数据
                List<AMSMeasureTool> wAMSMeasureToolList = mAMSMeasureToolService.SelectPOList(wLoginUser, wParams1,
                        Pagination.getMaxSize(), wErrorCode);
                //资质数据
                List<BMSQualification> wBMSQualificationList = mBMSQualificationService.SelectPOList(wLoginUser,
                        wParams1,
                        Pagination.getMaxSize(), wErrorCode);

                //翻译工装
                if (wResult.Result.FrockToolList != null && wResult.Result.FrockToolList.size() > 0) {
                    wResult.Result.FrockToolNames = StringUtils.Join(",",
                            wAMSFrockToolList.stream().filter(p -> wResult.Result.FrockToolList.stream().
                                    anyMatch(q -> q == p.ID)).map(p -> p.Name).collect(Collectors.toList()));
                }
                //翻译量器具
                if (wResult.Result.MeasureToolList != null && wResult.Result.MeasureToolList.size() > 0) {
                    wResult.Result.MeasureToolNames = StringUtils.Join(",",
                            wAMSMeasureToolList.stream().filter(p -> wResult.Result.MeasureToolList.stream().
                                    anyMatch(q -> q == p.ID)).map(p -> p.Name).collect(Collectors.toList()));
                }
                //翻译资质
                if (wResult.Result.QualificationsList != null && wResult.Result.QualificationsList.size() > 0) {
                    wResult.Result.QualificationNames = StringUtils.Join(",",
                            wBMSQualificationList.stream().filter(p -> wResult.Result.QualificationsList.stream().
                                    anyMatch(q -> q == p.ID)).map(p -> p.Name).collect(Collectors.toList()));
                }
            }

            wResult.AddFaultCode(wErrorCode);
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error(e.toString());
        }
        return wResult;
    }

    @Override
    public ServiceResult<Integer> DMS_AutoTriggerTask(BMSEmployee wLoginUser) {
        ServiceResult<Integer> wResult = new ServiceResult<>(0);
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            Calendar wBaseTime = Calendar.getInstance();
            wBaseTime.set(2010, 0, 1, 0, 0, 0);

            //①查询满足条件的规则
            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.put("EffectiveTime", wBaseTime);
            wParams.put("NextWorkTime", Calendar.getInstance());
            wParams.put("Active", 1);
            List<DMSMaintenanceRule> wDMSMaintenanceRuleList = mDMSMaintenanceRulePoService.SelectPOList(wLoginUser,
                    wParams, Pagination.getNewMaxSize(), wErrorCode);
            //②自动触发任务
            List<DMSMaintenanceRuleItem> wDMSMaintenanceRuleItemList;
            DMSMaintenanceItem wDMSMaintenanceItem;
            Map<String, Object> wParams1;
            for (DMSMaintenanceRule wDMSMaintenanceRule : wDMSMaintenanceRuleList) {
                wParams.clear();
                wParams.put("MaintenanceRuleID", wDMSMaintenanceRule.ID);
                //查询保养项
                wDMSMaintenanceRuleItemList =
                        mDMSMaintenanceRuleItemPoService.SelectPOList(wLoginUser, wParams, Pagination.getNewMaxSize()
                                , wErrorCode);
                for (DMSMaintenanceRuleItem wDMSMaintenanceRuleItem : wDMSMaintenanceRuleItemList) {
                    //查询保养项
                    wParams1 = new HashMap<String, Object>();
                    wParams1.put("ID", wDMSMaintenanceRuleItem.MaintenanceItemID);
                    wParams1.put("Active", 1);
                    wDMSMaintenanceItem =
                            DMSMaintenanceItemDAO.getInstance().SelectPO(wLoginUser, wParams1, wErrorCode);
                    if (wDMSMaintenanceItem != null && wDMSMaintenanceItem.ID > 0) {
                        //触发任务
                        DMSMaintenanceTaskDAO.getInstance().DMS_AutoTriggerTask(wLoginUser, wDMSMaintenanceRule,
                                wDMSMaintenanceRuleItem, wDMSMaintenanceItem, wErrorCode);
                        //维护规则的下次生效时间
                        if (wErrorCode.Result == 0) {
                            wDMSMaintenanceRule.NextWorkTime.add(Calendar.DAY_OF_MONTH, wDMSMaintenanceRule.Times);
                            mDMSMaintenanceRulePoService.UpdatePo(wLoginUser, wDMSMaintenanceRule, wErrorCode);
                        }
                    }
                }
            }

            wResult.AddFaultCode(wErrorCode);
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error(e.toString());
        }
        return wResult;
    }

    @Override
    public ServiceResult<Integer> DMS_UpdateMaintenanceItem(BMSEmployee wLoginUser,
                                                            DMSMaintenanceItem wDMSMaintenanceItem) {
        ServiceResult<Integer> wResult = new ServiceResult<>(0);
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            wDMSMaintenanceItem.setUserInfo(wLoginUser);
            DMSMaintenanceItemDAO.getInstance().UpdatePo(wLoginUser, wDMSMaintenanceItem, wErrorCode);
            if (wDMSMaintenanceItem.ID > 0) {
                Calendar wBaseTime = Calendar.getInstance();
                wBaseTime.set(2010, 0, 1, 0, 0, 0);
                //保存保养规则
                for (DMSMaintenanceRule wDMSMaintenanceRule : wDMSMaintenanceItem.MaintenanceRuleList) {
                    wDMSMaintenanceRule.setUserInfo(wLoginUser);
                    wDMSMaintenanceRule.ConfigurationID = wDMSMaintenanceItem.ConfigurationID;
                    wDMSMaintenanceRule.MaintenanceItemList =
                            new ArrayList<>(Collections.singletonList(wDMSMaintenanceItem));
                    if (wDMSMaintenanceRule.ID == 0 && wDMSMaintenanceRule.EffectiveTime.compareTo(wBaseTime) > 0) {
//                        wDMSMaintenanceRule.NextWorkTime = (Calendar) wDMSMaintenanceRule.EffectiveTime.clone();
//                        wDMSMaintenanceRule.NextWorkTime.add(Calendar.DAY_OF_MONTH, wDMSMaintenanceRule.Times);
                        wDMSMaintenanceRule.NextWorkTime = Calendar.getInstance();//立即生效
                    }
                    DRMServiceImpl.getInstance().DMS_UpdateMaintenanceRule(wLoginUser,
                            wDMSMaintenanceRule);
                }
            }

            wResult.AddFaultCode(wErrorCode);
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error(e.toString());
        }
        return wResult;
    }

    @Override
    public ServiceResult<Integer> DMS_ResetTask(BMSEmployee wLoginUser, int wDeviceID, int wMaintenanceLevel) {
        ServiceResult<Integer> wResult = new ServiceResult<>(0);
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            //①查询今日设备点检项维保任务
            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.put("DeviceID", wDeviceID);
            wParams.put("MaintenanceLevel", wMaintenanceLevel);
            wParams.put("DStartTime", CalendarTool.getDate());
            wParams.put("DEndTime", CalendarTool.getDateMaxMill());
            List<DMSMaintenanceItemTask> wDMSMaintenanceItemTaskList =
                    mDMSMaintenanceItemTaskService.SelectPOList(wLoginUser, wParams, Pagination.getNewMaxSize(),
                            wErrorCode);
            if (wDMSMaintenanceItemTaskList.size() == 0) {
                wResult.FaultCode += "任务重置失败：今日无任务!";
                return wResult;
            }
            //②若有未完成项，则报错
            if (wDMSMaintenanceItemTaskList.stream().anyMatch(p -> p.Status != DMSItemTaskStatus.ToRepair.getValue())) {
                DMSMaintenanceItemTask wDMSMaintenanceItemTask =
                        wDMSMaintenanceItemTaskList.stream().filter(p -> p.Status != DMSItemTaskStatus.ToRepair.getValue()).findFirst().get();
                wResult.FaultCode += StringUtils.Format("任务重置失败：【{0}】项未完成!",
                        wDMSMaintenanceItemTask.MaintenanceItemName);
                return wResult;
            }
            //③提取点检项ID集合
            List<Integer> wItemIDList =
                    wDMSMaintenanceItemTaskList.stream().map(p -> p.MaintenanceItemID).distinct().collect(Collectors.toList());
            //④保养项任务分组
            Map<Integer, List<DMSMaintenanceItemTask>> wItemIDTaskListMap = wDMSMaintenanceItemTaskList.stream()
                    .collect(Collectors.groupingBy(DMSMaintenanceItemTask::getMaintenanceItemID));
            //④依次取最新的一版，复制任务
            List<DMSMaintenanceItemTask> dmsMaintenanceItemTasks;
            DMSMaintenanceItemTask dmsMaintenanceItemTask;
            for (int wMaintenanceItemID : wItemIDList) {
                dmsMaintenanceItemTasks = wItemIDTaskListMap.get(wMaintenanceItemID);
                dmsMaintenanceItemTask =
                        dmsMaintenanceItemTasks.stream().max(Comparator.comparing(DMSMaintenanceItemTask::getEditTime)).get();
                dmsMaintenanceItemTask.ID = 0;
                dmsMaintenanceItemTask.Code = "";
                dmsMaintenanceItemTask.setUserInfo(wLoginUser);
                dmsMaintenanceItemTask.Status = DMSItemTaskStatus.ToDispatch.getValue();
                dmsMaintenanceItemTask.DispatchPersonID = 0;
                dmsMaintenanceItemTask.DispatchTime = CalendarTool.getBasicDate();
                dmsMaintenanceItemTask.DispatchRemark = "";
                dmsMaintenanceItemTask.WorkerID = 0;
                dmsMaintenanceItemTask.WorkerTime = CalendarTool.getBasicDate();
                dmsMaintenanceItemTask.WorkerRemark = "";
                dmsMaintenanceItemTask.CheckerID = 0;
                dmsMaintenanceItemTask.CheckerTime = CalendarTool.getBasicDate();
                dmsMaintenanceItemTask.CheckerRemark = "";
                dmsMaintenanceItemTask.Remark = "";
                dmsMaintenanceItemTask.Result = 0;
                dmsMaintenanceItemTask.ImageList = new ArrayList<>();
                dmsMaintenanceItemTask.PlanDate = Calendar.getInstance();
                mDMSMaintenanceItemTaskService.UpdatePo(wLoginUser, dmsMaintenanceItemTask, wErrorCode);
            }

            wResult.setFaultCode(ExceptionTypes.getEnumType(wErrorCode.Result).getLabel());
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error("DMS_ResetTask", e);
        }
        return wResult;
    }

    @Override
    public ServiceResult<Integer> DRM_ImportMaintenanceItem(BMSEmployee wLoginUser, ExcelData wExcelData) {
        ServiceResult<Integer> wResult = new ServiceResult<>(0);
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            if (wExcelData == null || wExcelData.sheetData == null || wExcelData.sheetData.size() <= 0) {
                wResult.FaultCode += "导入失败：Excel格式错误!!!";
                return wResult;
            }

            ExcelSheetData wExcelSheetData = wExcelData.sheetData.get(0);
            if (wExcelSheetData.lineData == null || wExcelSheetData.lineData.size() <= 1) {
                wResult.FaultCode += "导入失败：Excel无内容!!!";
                return wResult;
            }

            //①设备构型
            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.put("Active", 1);
            List<DMSConfiguration> wDMSConfigurationList = mDMSConfigurationService.SelectPOList(wLoginUser, wParams,
                    Pagination.getNewMaxSize(),
                    wErrorCode);
            if (wDMSConfigurationList == null || wDMSConfigurationList.size() <= 0) {
                wResult.FaultCode += "导入失败：未获取到设备构型信息!!!";
                return wResult;
            }
            Map<String, Integer> wNameIDConfigurationMap =
                    wDMSConfigurationList.stream().collect(Collectors.toMap(DMSConfiguration::getName
                            , DMSConfiguration::getID));

            //①设备台账
            wParams.clear();
            wParams.put("Active", 1);
            List<DMSDeviceLedger> wDMSDeviceLedgerList = mDMSDeviceLedgerService.SelectPOList(wLoginUser, wParams,
                    Pagination.getNewMaxSize(),
                    wErrorCode);
            if (wDMSConfigurationList == null || wDMSConfigurationList.size() <= 0) {
                wResult.FaultCode += "导入失败：未获取到设备台账信息!!!";
                return wResult;
            }
            Map<String, Integer> wNameIDDeviceLedgerMap =
                    wDMSDeviceLedgerList.stream().collect(Collectors.toMap(DMSDeviceLedger::getName
                            , DMSDeviceLedger::getID));

            List<DMSMaintenanceItem> wDMSMaintenanceItemList = new ArrayList<>();
            DMSMaintenanceItem wDMSMaintenanceItem;
            for (int i = 0; i < wExcelSheetData.lineData.size(); i++) {
                if (i == 0) {
                    continue;
                }

                ExcelLineData wExcelLineData = wExcelSheetData.lineData.get(i);
                int wIndex = 0;

                //设备名称
                String wCol1 = wExcelLineData.colData.get(wIndex++);
                if (StringUtils.isEmpty(wCol1)) {
                    continue;
                }
                if (!wNameIDDeviceLedgerMap.containsKey(wCol1)) {
                    wResult.FaultCode += StringUtils.Format("导入失败：第【{0}】行数据有误，设备台账【{1}】不存在!!!", i + 1, wCol1);
                    return wResult;
                }
                if (!wNameIDConfigurationMap.containsKey(wCol1)) {
                    wResult.FaultCode += StringUtils.Format("导入失败：第【{0}】行数据有误，设备构型【{1}】不存在!!!", i + 1, wCol1);
                    return wResult;
                }
                //保养等级
                String wCol2 = wExcelLineData.colData.get(wIndex++);
                DMSMaintenanceLevel wDMSMaintenanceLevel = DMSMaintenanceLevel.getEnumType(wCol2);
                if (wDMSMaintenanceLevel.getValue() <= 0) {
                    wResult.FaultCode += StringUtils.Format("导入失败：第【{0}】行数据有误，保养等级【{1}】输入值有误!!!", i + 1, wCol2);
                    return wResult;
                }
                //保养项名称
                String wCol3 = wExcelLineData.colData.get(wIndex++);
                if (StringUtils.isEmpty(wCol3)) {
                    wResult.FaultCode += StringUtils.Format("导入失败：第【{0}】行数据有误，保养项名称不能为空!!!", i + 1);
                    return wResult;
                }
                //保养项描述
                String wCol4 = wExcelLineData.colData.get(wIndex++);
                if (StringUtils.isEmpty(wCol4)) {
                    wResult.FaultCode += StringUtils.Format("导入失败：第【{0}】行数据有误，保养项描述不能为空!!!", i + 1);
                    return wResult;
                }
                //保养工时
                String wCol5 = wExcelLineData.colData.get(wIndex++);
                //顺序
                String wCol6 = wExcelLineData.colData.get(wIndex++);
                //保养周期
                String wCol7 = wExcelLineData.colData.get(wIndex++);

                wDMSMaintenanceItem = new DMSMaintenanceItem();
                wDMSMaintenanceItem.DeviceID = wNameIDDeviceLedgerMap.get(wCol1);
                wDMSMaintenanceItem.ConfigurationID = wNameIDConfigurationMap.get(wCol1);
                wDMSMaintenanceItem.setUserInfo(wLoginUser);
                wDMSMaintenanceItem.Name = wCol3;
                wDMSMaintenanceItem.Description = wCol4;
                wDMSMaintenanceItem.WorkTime = StringUtils.parseDouble(wCol5);
                wDMSMaintenanceItem.OrderNum = StringUtils.parseInt(wCol6);
                wDMSMaintenanceItem.Type = DMSMaintenanceItemType.MAINTENANCE.getValue();
                wDMSMaintenanceItem.MaintenanceLevel = wDMSMaintenanceLevel.getValue();
                wDMSMaintenanceItem.Active = 1;
                //添加保养规则
                int wRuleTimes = StringUtils.parseInt(wCol7);
                if (wRuleTimes > 0) {
                    DMSMaintenanceRule wDMSMaintenanceRule = new DMSMaintenanceRule();
                    wDMSMaintenanceRule.Name = wCol2;
                    wDMSMaintenanceRule.DeviceID = wDMSMaintenanceItem.DeviceID;
                    wDMSMaintenanceRule.ConfigurationID = wDMSMaintenanceItem.ConfigurationID;
                    wDMSMaintenanceRule.Type = 2;
                    wDMSMaintenanceRule.Times = wRuleTimes;
                    wDMSMaintenanceRule.Active = 1;
                    wDMSMaintenanceItem.MaintenanceRuleList.add(wDMSMaintenanceRule);
                }

                wDMSMaintenanceItemList.add(wDMSMaintenanceItem);
            }
            //保存设备维保项点
            ServiceResult<Integer> integerServiceResult;
            for (DMSMaintenanceItem wUpdateItem : wDMSMaintenanceItemList) {
                integerServiceResult =
                        DRMServiceImpl.getInstance().DMS_UpdateMaintenanceItem(wLoginUser,
                                wUpdateItem);
                if (StringUtils.isNotEmpty(integerServiceResult.FaultCode)) {
                    wResult.FaultCode += integerServiceResult.FaultCode;
                    return wResult;
                }
            }

            wResult.setFaultCode(ExceptionTypes.getEnumType(wErrorCode.Result).getLabel());
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error("MSS_ImportMaterial", e);
        }
        return wResult;
    }

    @Override
    public ServiceResult<String> DRM_ExportMaintenanceItem(BMSEmployee wLoginUser, int wConfigurationID,
                                                           int wMaintenanceLevel, int wActive) {
        ServiceResult<String> wResult = new ServiceResult<>();
        wResult.Result = "";
        try {
            OutResult<Integer> wErrorCode = new OutResult<>(0);

            Map<String, Object> wParams = new HashMap<String, Object>();
            wParams.put("ConfigurationID", wConfigurationID);
            wParams.put("MaintenanceLevel", wMaintenanceLevel);
            wParams.put("Active", wActive);
            wParams.put("Type", DMSMaintenanceItemType.MAINTENANCE.getValue());
            List<DMSMaintenanceItem> wDMSMaintenanceItemList = mDMSMaintenanceItemService.SelectPOList(wLoginUser,
                    wParams,
                    Pagination.getNewMaxSize(),
                    wErrorCode);
            if (wDMSMaintenanceItemList == null || wDMSMaintenanceItemList.size() == 0) {
                wResult.FaultCode += "导出失败：维保项点为空!";
                return wResult;
            }
            //查询规则子项
            wParams.clear();
            wParams.put("MaintenanceItemID", StringUtils.Join(",",
                    wDMSMaintenanceItemList.stream().map(p -> p.ID).distinct().collect(Collectors.toList())));
            List<DMSMaintenanceRuleItem> wDMSMaintenanceRuleItemList =
                    mDMSMaintenanceRuleItemPoService.SelectPOList(wLoginUser, wParams, Pagination.getNewMaxSize(),
                            wErrorCode);
            //查询保养规则
            List<DMSMaintenanceRule> wDMSMaintenanceRuleList = new ArrayList<>();
            if (wDMSMaintenanceRuleItemList.size() > 0) {
                wParams.clear();
                wDMSMaintenanceRuleList = mDMSMaintenanceRulePoService.SelectPOList(wLoginUser,
                        wDMSMaintenanceRuleItemList.stream().map(p -> p.MaintenanceRuleID).distinct().collect(Collectors.toList()), wParams, Pagination.getNewMaxSize(),
                        wErrorCode);
            }

            MyExcelSheet wMyExcelSheet = DRM_GetMyExcelSheet_MaintenanceItem(wDMSMaintenanceItemList,
                    wDMSMaintenanceRuleItemList, wDMSMaintenanceRuleList);

            List<MyExcelSheet> wMyExcelSheetList =
                    new ArrayList<MyExcelSheet>(Collections.singletonList(wMyExcelSheet));

            wResult.Result = ExcelUtil.ExportData(wMyExcelSheetList, "维保项点");

            wResult.setFaultCode(ExceptionTypes.getEnumType(wErrorCode.Result).getLabel());
        } catch (Exception e) {
            wResult.FaultCode += e.toString();
            logger.error("DRM_ExportMaintenanceItem", e);
        }
        return wResult;
    }

    private MyExcelSheet DRM_GetMyExcelSheet_MaintenanceItem(List<DMSMaintenanceItem> wDMSMaintenanceItemList,
                                                             List<DMSMaintenanceRuleItem> wDMSMaintenanceRuleItemList
            , List<DMSMaintenanceRule> wDMSMaintenanceRuleList) {
        MyExcelSheet wResult = new MyExcelSheet();
        try {
            Map<Integer, DMSMaintenanceRule> wIDRuleMap =
                    wDMSMaintenanceRuleList.stream().collect(Collectors.toMap(DMSMaintenanceRule::getID
                            , p -> p));

            wResult.TitleName = "";
            wResult.SheetName = "维保项点列表";
            wResult.HeaderList = new ArrayList<>(Arrays.asList("设备名称", "保养等级", "保养项名称", "保养项描述", "保养工时", "顺序", "保养周期"));
            wResult.DataList = new ArrayList<>();
            // 排序
            wDMSMaintenanceItemList.sort(Comparator.comparing(DMSMaintenanceItem::getOrderNum));
            List<String> wValueList;

            String wTimesStr = "";
            for (DMSMaintenanceItem wDMSMaintenanceItem : wDMSMaintenanceItemList) {
                int wTimes = 0;
                //获取保养周期
                if (wDMSMaintenanceRuleItemList.stream().anyMatch(p -> p.MaintenanceItemID == wDMSMaintenanceItem.ID)) {
                    List<DMSMaintenanceRuleItem> wItemList =
                            wDMSMaintenanceRuleItemList.stream().filter(p -> p.MaintenanceItemID == wDMSMaintenanceItem.ID).collect(Collectors.toList());
                    for (DMSMaintenanceRuleItem wDMSMaintenanceRuleItem : wItemList) {
                        if (wIDRuleMap.containsKey(wDMSMaintenanceRuleItem.MaintenanceRuleID)) {
                            DMSMaintenanceRule dmsMaintenanceRule =
                                    wIDRuleMap.get(wDMSMaintenanceRuleItem.MaintenanceRuleID);
                            if (dmsMaintenanceRule.Active == 1) {
                                wTimes = dmsMaintenanceRule.Times;
                            }
                        }
                    }
                }

                if (wTimes > 0) {
                    wTimesStr = String.valueOf(wTimes);
                } else {
                    wTimesStr = "";
                }

                wValueList = new ArrayList<>(Arrays.asList(wDMSMaintenanceItem.DeviceName,
                        DMSMaintenanceLevel.getEnumType(wDMSMaintenanceItem.MaintenanceLevel).getLabel(),
                        wDMSMaintenanceItem.Name, wDMSMaintenanceItem.Description,
                        String.valueOf(wDMSMaintenanceItem.WorkTime), String.valueOf(wDMSMaintenanceItem.OrderNum),
                        wTimesStr));
                wResult.DataList.add(wValueList);
            }
        } catch (Exception e) {
            logger.error("DRM_GetMyExcelSheet_MaintenanceItem", e);
        }
        return wResult;

    }

    //endregion
}
